package com.aidisp.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.aidisp.exception.DefaultException;

public class LogInterceptor implements HandlerInterceptor {
	private static final Logger logger = Logger.getLogger(LogInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		long requestArriveTime = System.currentTimeMillis();
		request.setAttribute("requestArriveTime", requestArriveTime);
		logger.info("remote host:"+request.getRemoteAddr()+":"+request.getRemotePort());
		logger.info("request arrive time:"+requestArriveTime);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		logger.info("execute "+request.getRequestURI()+" finished");
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		long responseFinishTime = System.currentTimeMillis();
		long requestArriveTime = (Long)request.getAttribute("requestArriveTime");
		logger.info("response finish time:"+responseFinishTime);
		long processingTime = responseFinishTime-requestArriveTime;
		if(processingTime<500){
			logger.info("processing time:"+processingTime);
		}else{
			logger.warn(request.getRemoteAddr()+":"+request.getRemotePort()+" execute "+request.getRequestURI()+" processing time:"+processingTime);
		}
	}
}
